package io.dirac.shiro;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "jwt")  // 根据配置文件中的 jwt 字段注入属性值
public class JwtUtils {

    private String secret;
    private long expire;  // 有效时间（秒）
    private String header;

    // 根据用户 ID 生成 JWT Token
    public String generateToken(long userId) {

        Date nowDate = new Date();

        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        System.out.println(secret);

        return Jwts.builder()
                .setHeaderParam("type", "JWT")
                .setSubject(userId + "")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    // 根据 token 获取 jwt Claim
    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.debug("validate is token error ", e);
            return null;
        }
    }

    // token是否过期
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

}
